<template>
    <div class="doctor-form-container">
        <!-- 标题 -->
        <div class="form-header">
            <h3>医生信息</h3>
        </div>

        <!-- 表单 -->
        <el-form :model="doctorForm" label-width="110px" size="default" ref="formRef" :rules="rules"
            class="doctor-form">
            <el-row :gutter="20">
                <!-- 第一行 -->
                <el-col :span="8">
                    <el-form-item label="医生编号">
                        <el-input v-model="doctorForm.doctorId" :disabled="true" />
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item label="账号" prop="phone" required>
                        <el-input v-model="doctorForm.phone" placeholder="请输入手机号或邮箱" />
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item label="医生头像">
                        <div class="avatar-upload">
                            <el-avatar :size="50" :src="doctorForm.avatar" />
                            <!-- <el-button type="primary" link>+点击上传</el-button> -->
                        </div>
                    </el-form-item>
                </el-col>
            </el-row>

            <el-row :gutter="20">
                <!-- 第二行 -->
                <el-col :span="8">
                    <el-form-item label="医生姓名" prop="name" required>
                        <el-input v-model="doctorForm.name" placeholder="请输入" />
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item label="医生角色" prop="roleId" required>
                        <el-select v-model="doctorForm.roleId" placeholder="请选择" style="width: 100%">
                            <el-option label="请选择" value="" />
                            <el-option v-for="item in roleList" :key="item._id" :label="item.name" :value="item._id" />
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item label="登录密码" prop="password" :required="!isEdit">
                        <el-input v-model="doctorForm.password" type="password"
                            :placeholder="isEdit ? '留空则不修改密码' : '请输入登录密码'" />
                    </el-form-item>
                </el-col>
            </el-row>

            <el-row :gutter="20">
                <!-- 第三行 -->
                <el-col :span="8">
                    <el-form-item label="性别">
                        <el-select v-model="doctorForm.gender" placeholder="请选择" style="width: 100%">
                            <el-option label="请选择" value="" />
                            <el-option label="男" value="1" />
                            <el-option label="女" value="0" />
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item label="医生所属机构" prop="organizationId" required>
                        <el-select v-model="doctorForm.organizationId" placeholder="请选择机构" style="width: 100%">
                            <el-option label="请选择" value="" />
                            <el-option v-for="item in organizationList" :key="item._id" :label="item.name"
                                :value="item._id" />
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <!-- 空白区域 -->
                </el-col>
            </el-row>

            <el-row :gutter="20">
                <!-- 医生简介 -->
                <el-col :span="24">
                    <el-form-item label="医生简介">
                        <el-input v-model="doctorForm.intro" type="textarea" :rows="6" placeholder="请输入" />
                    </el-form-item>
                </el-col>
            </el-row>

            <el-row :gutter="20">
                <!-- 医生技能 -->
                <el-col :span="24">
                    <el-form-item label="医生技能">
                        <el-input v-model="doctorForm.skill" type="textarea" :rows="6" placeholder="请输入" />
                    </el-form-item>
                </el-col>
            </el-row>

            <!-- 操作按钮 -->
            <div class="form-actions">
                <el-button type="primary" @click="handleSubmit" :loading="submitting">
                    保存
                </el-button>
                <el-button @click="handleCancel">返回</el-button>
            </div>
        </el-form>
    </div>
</template>

<script setup lang="ts">
import { onMounted, ref, computed } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { addDoctorsApi, updateDoctorsApi, findRoleApi, getDoctorsDetailApi, findOrganizationsApi } from '@/api/doctors'

// 路由实例
const route = useRoute()
const router = useRouter()

// 表单引用
const formRef = ref()

// 获取医生ID（从路由参数获取）
const doctorId = computed(() => {
    return route.params._id as string
})

// 是否为编辑模式
const isEdit = computed(() => !!doctorId.value)

// 提交状态
const submitting = ref(false)

// 表单数据
const doctorForm = ref({
    doctorId: '',
    phone: '',
    avatar: 'https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png',
    name: '',
    password: '',
    gender: '',
    intro: '',
    roleId: '',
    skill: '',
    organizationId: ''
})

// 表单验证规则
const rules = {
    phone: [
        { required: true, message: '请输入手机号或邮箱', trigger: 'blur' },
        // {
        //     pattern: /^(1[3-9]\d{9}|[\w\.-]+@[\w\.-]+\.\w+)$/,
        //     message: '请输入正确的手机号或邮箱格式',
        //     trigger: 'blur'
        // }
    ],
    name: [
        { required: true, message: '请输入医生姓名', trigger: 'blur' },
        // { min: 2, max: 20, message: '姓名长度应在2-20个字符之间', trigger: 'blur' }
    ],
    roleId: [
        { required: true, message: '请选择医生角色', trigger: 'change' }
    ],
    organizationId: [
        { required: true, message: '请选择所属机构', trigger: 'change' }
    ],
    // password: [
    //     {
    //         validator: (_rule: any, value: string, callback: Function) => {
    //             if (!isEdit.value && !value) {
    //                 callback(new Error('新增医生时密码不能为空'))
    //             } else if (value && value.length < 6) {
    //                 callback(new Error('密码长度不能少于6位'))
    //             } else {
    //                 callback()
    //             }
    //         },
    //         trigger: 'blur'
    //     }
    // ]
}

// 机构列表
const organizationList = ref<any[]>([])

// 角色列表
const roleList = ref<any[]>([])

onMounted(() => {
    findOrganizations()
    findRole()

    // 如果是编辑模式，加载医生数据
    if (isEdit.value) {
        loadDoctorData()
    } else {
        // 新增模式，生成医生编号
        doctorForm.value.doctorId = generateDoctorId()
    }
})

// 生成医生编号
function generateDoctorId() {
    const timestamp = Date.now()
    return timestamp.toString()
}

// 获取机构列表
function findOrganizations() {
    findOrganizationsApi()
        .then(res => {
            if (res.code == 200) {
                organizationList.value = res.data.rows
            }
        })
}

// 获取角色列表
function findRole() {
    findRoleApi()
        .then(res => {
            if (res.code == 200) {
                roleList.value = res.data.rows
            }
        })
}

// 加载医生数据（编辑模式）
const loadDoctorData = async () => {
    if (!doctorId.value) return

    const res = await getDoctorsDetailApi({ _id: doctorId.value })

    if (res.code === 200) {
        const data = res.data
        doctorForm.value = {
            doctorId: data._id,
            phone: data.phone || '',
            avatar: data.avatar || 'https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png',
            name: data.name || '',
            password: data.password || '',
            gender: data.gender !== undefined ? String(data.gender) : '',
            intro: data.intro || '',
            roleId: data.roleId?._id || '',
            skill: data.skill || '',
            organizationId: getOrganizationId(data)
        }
    } else {
        ElMessage.error(res.data.message)
    }
}

// 获取机构ID
function getOrganizationId(data: any) {
    if (data.organizationId) {
        if (typeof data.organizationId === 'object' && data.organizationId._id) {
            return data.organizationId._id
        }
        if (typeof data.organizationId === 'string') {
            return data.organizationId
        }
    }

    if (data.teamIds && data.teamIds.length > 0) {
        const firstTeam = data.teamIds[0]
        if (firstTeam.organizationId) {
            if (typeof firstTeam.organizationId === 'object' && firstTeam.organizationId._id) {
                return firstTeam.organizationId._id
            }
            if (typeof firstTeam.organizationId === 'string') {
                return firstTeam.organizationId
            }
        }
    }

    return ''
}

// 提交表单
const handleSubmit = async () => {
    if (!formRef.value) return

    // 表单验证
    await formRef.value.validate()

    submitting.value = true

    let res
    if (isEdit.value) {
        // 编辑模式：调用更新接口
        const updateData = {
            ...doctorForm.value,
            _id: doctorForm.value.doctorId
        }

        // 如果密码为空，则不提交密码字段
        if (!updateData.password) {
            delete (updateData as any).password
        }

        res = await updateDoctorsApi(updateData)
    } else {
        // 新增模式：调用新增接口
        res = await addDoctorsApi(doctorForm.value)
    }

    console.log('API响应:', res)

    if (res.code === 200) {
        ElMessage.success(isEdit.value ? '更新成功' : '新增成功')
        // 跳转回列表页
        // router.push('/data/doctor/list')
        router.back();
    } else {
        ElMessage.error(res.message)
    }

    submitting.value = false
}

// 取消操作
const handleCancel = () => {
    router.back()
}
</script>

<style scoped>
.doctor-form-container {
    background: #fff;
    padding: 0;
    margin: 0;
}

.form-header {
    background: #f8f9fa;
    padding: 15px 20px;
    border-left: 4px solid #409eff;
    margin-bottom: 20px;
}

.form-header h3 {
    margin: 0;
    color: #333;
    font-size: 16px;
    font-weight: 500;
}

.doctor-form {
    padding: 0 20px;
}

.avatar-upload {
    display: flex;
    align-items: center;
    gap: 10px;
}

.form-actions {
    padding: 20px 0;
    text-align: left;
    border-top: 1px solid #ebeef5;
    margin-top: 20px;
}

.form-actions .el-button {
    margin-right: 10px;
}

/* 调整表单项间距 */
.el-form-item {
    margin-bottom: 18px;
}

/* 调整标签宽度 */
.doctor-form .el-form-item__label {
    font-weight: normal;
    color: #606266;
}

/* 文本域样式 */
.el-textarea .el-textarea__inner {
    resize: none;
}
</style>